# encoding:utf-8

import requests
import base64


class bdimg:
    # 获取access_token
    def get_acc(self):
        ak = 'ytG1sGteMGK0ID1cpOQWhioI'
        sk = 'OKHnPdCNtZsGlSLwhbGzkUOgkQLcdI3i'
        # client_id 为官网获取的AK， client_secret 为官网获取的SK
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ak + '&client_secret=' + sk
        response = requests.get(host)
        if response:
            access_token = response.json()['access_token']
            return access_token

    # 通用文字识别
    def ty_text(self, image_path='1.png'):

        # 普通可以使用50000次/天
        # request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
        # 高清可以使用500次/天
        request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"

        # 二进制方式打开图片文件
        f = open(image_path, 'rb')
        img = base64.b64encode(f.read())
        params = {"image": img}
        request_url = request_url + "?access_token=" + self.get_acc()
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        res = requests.post(request_url, data=params, headers=headers)
        if res.json():
            return res.json()['words_result']


if __name__ == '__main__':
    ojb = bdimg()
    ojb.ty_text()
